package com.distribute.framework.core.web.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.distribute.framework.core.lang.Protocol.PageInfo;

@SuppressWarnings("unchecked")
public class  Page<T>  implements java.io.Serializable
{
	boolean prev;//是否有上一页
	boolean next;//是否有下一页
	int  	size;//每页记录数
	int    total;//总页数
	long 	count;//总记录数
	int    index;//当前页	
	List    result;//结果集	
	
	public Page(int index,int size, long count, List result)
	{
		super();
		this.total =(int) count/size+((count%size)>0?1:0);
		this.prev=index>0;
		this.next=(total-1)>index;
		this.size = size;
		this.count = count;
		this.index = (index>=total)?(total-1):index;
		this.index=this.index<0?0:this.index;
		this.result = result==null?new ArrayList():result;
	}
	
	public static long test(int index,int size,long count){		
		int total=(int) count/size+((count%size)>0?1:0);
		index=(index>=total)?(total-1):index;
		index=index<0?0:index;
		return index*size;
	}

	public boolean isPrev()
	{
		return prev;
	}

	public void setPrev(boolean prev)
	{
		this.prev = prev;
	}

	public boolean isNext()
	{
		return next;
	}

	public void setNext(boolean next)
	{
		this.next = next;
	}

	public int getSize()
	{
		return size;
	}

	public void setSize(int size)
	{
		this.size = size;
	}

	public int getTotal()
	{
		return total;
	}

	public void setTotal(int total)
	{
		this.total = total;
	}

	public long getCount()
	{
		return count;
	}

	public void setCount(long count)
	{
		this.count = count;
	}

	public int getIndex()
	{
		return index;
	}

	public void setIndex(int index)
	{
		this.index = index;
	}

	public List<T> getResult()
	{
		return result;
	}

	public void setResult(List result)
	{
		this.result = result;
	}
	
	/**对象转json**/
	public Map toJSON(){
		return toJSON(false);
	}
	public Map toJSON(boolean simple){
		Map json = new HashMap();
		Map pageInfo = new HashMap();
		pageInfo.put("count", this.count);
		pageInfo.put("next", this.next);
		pageInfo.put("size", this.size);
		pageInfo.put("prev", this.prev);
		pageInfo.put("index", this.index);
		pageInfo.put("total", this.total);
		json.put("pageInfo", pageInfo);
		List list = new ArrayList();
		for(Object object:result){
			Method toJSONMethod = null;
			try {
				toJSONMethod = object.getClass().getMethod("toJSON", Boolean.class);
				if(toJSONMethod!=null){
					list.add(toJSONMethod.invoke(object, simple));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		json.put("list", list);
		return json;
	}
	

}